<template>
  <div class="page-container workflow-editor-page">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="handleCancel" text>
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>{{ isNew ? '创建工作流' : '编辑工作流' }}</h2>
      </div>
    </div>

    <el-card class="basic-info-card">
      <el-form :model="form" label-width="120px" :inline="true">
        <el-form-item label="工作流名称" required>
          <el-input v-model="form.name" placeholder="请输入工作流名称" style="width: 300px" />
        </el-form-item>
        <el-form-item label="工作流描述">
          <el-input v-model="form.description" placeholder="请输入工作流描述" style="width: 400px" />
        </el-form-item>
        <el-form-item label="定时调度">
          <el-switch v-model="form.cron_enabled" style="margin-right: 10px" />
          <el-input
            v-if="form.cron_enabled"
            v-model="form.cron_expression"
            placeholder="Cron表达式，如: 0 2 * * *"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="editor-card">
      <WorkflowEditor
        ref="editorRef"
        v-model="workflowData"
        @save="handleSaveWorkflow"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import WorkflowEditor from '@/components/WorkflowEditor/index.vue'

const route = useRoute()
const router = useRouter()
const workflowStore = useWorkflowStore()

const isNew = computed(() => route.params.id === 'new')
const editorRef = ref(null)

const form = ref({
  name: '',
  description: '',
  cron_enabled: false,
  cron_expression: ''
})

const workflowData = ref({
  nodes: [],
  edges: []
})

const handleSaveWorkflow = async (data) => {
  if (!form.value.name) {
    ElMessage.warning('请输入工作流名称')
    return
  }

  try {
    const workflowPayload = {
      name: form.value.name,
      description: form.value.description,
      cron_enabled: form.value.cron_enabled,
      cron_expression: form.value.cron_expression,
      workflow_definition: data || workflowData.value
    }

    if (isNew.value) {
      await workflowStore.createWorkflow(workflowPayload)
      ElMessage.success('工作流创建成功')
    } else {
      await workflowStore.updateWorkflow(route.params.id, workflowPayload)
      ElMessage.success('工作流更新成功')
    }
    router.push('/workflows')
  } catch (error) {
    console.error('保存工作流失败:', error)
    ElMessage.error('保存工作流失败')
  }
}

const handleCancel = () => {
  router.push('/workflows')
}

// 将后端格式转换为 Vue Flow 格式
const convertFromBackendFormat = (backendDefinition) => {
  if (!backendDefinition || !backendDefinition.nodes) {
    return { nodes: [], edges: [] }
  }

  const edges = []
  const nodePositions = new Map()

  // 第一遍：收集所有节点和边
  backendDefinition.nodes.forEach((node, index) => {
    // 简单的自动布局：水平排列
    const x = 180 + index * 300
    const y = 90
    nodePositions.set(node.id, { x, y })

    // 如果节点有 next，创建边
    if (node.next) {
      edges.push({
        id: `edge_${node.id}_${node.next}`,
        type: 'smoothstep',
        source: node.id,
        target: node.next,
        animated: true,
        label: '',
        data: {}
      })
    }
  })

  // 第二遍：转换节点格式
  const nodes = backendDefinition.nodes.map(node => {
    const position = nodePositions.get(node.id) || { x: 0, y: 0 }

    return {
      id: node.id,
      type: node.type,
      position,
      data: {
        label: node.name || node.type,
        config: node.config || {}
      }
    }
  })

  return { nodes, edges }
}

onMounted(async () => {
  if (!isNew.value) {
    try {
      const data = await workflowStore.fetchWorkflowDetail(route.params.id)
      form.value = {
        name: data.name,
        description: data.description,
        cron_enabled: data.cron_enabled,
        cron_expression: data.cron_expression
      }
      if (data.workflow_definition) {
        // 将后端格式转换为 Vue Flow 格式
        workflowData.value = convertFromBackendFormat(data.workflow_definition)
      }
    } catch (error) {
      console.error('获取工作流详情失败:', error)
      ElMessage.error('获取工作流详情失败')
    }
  }
})
</script>

<style lang="scss" scoped>
.workflow-editor-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);

  .page-header {
    margin-bottom: 16px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
      }
    }
  }

  .basic-info-card {
    margin-bottom: 16px;
  }

  .editor-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    :deep(.el-card__body) {
      flex: 1;
      padding: 0;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
}
</style>
